package com.github.kezhenxu94.playground.java.concurrent.itc;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <pre>
 * 
 * {@link CountDownLatch} - 闭锁
 * 
 * 闭锁能够协调线程间的动作，闭锁一经打开，不可重新使用
 * 
 * </pre>
 * 
 * @author kezhenxu
 *
 */
public class StudyCountDownLatch {

	public static void main(String[] args) throws InterruptedException {
		final CountDownLatch startLatch = new CountDownLatch(1);
		final CountDownLatch endLatch = new CountDownLatch(10);
		final ExecutorService executor = Executors.newCachedThreadPool();
		for (int i = 0; i < 10; i++) {
			executor.execute(() -> {
				try {
					startLatch.await();
					System.out.println(Thread.currentThread() + " pass the latch now.");
					Thread.sleep(3000);
					endLatch.countDown();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			});
		}
		System.out.println("get everything ready...");
		Thread.sleep(3000);
		startLatch.countDown();

		endLatch.await();
		System.out.println();
		System.out.println(Thread.currentThread() + " pass the latch now.");

		executor.shutdown();
	}
}
